local ClientOHOH = _G.ClientOHOH;

local M = ClientOHOH.class.new(script, ClientOHOH.files.OHOHOLYBUIBase());
local CommonOHOH =_G.CommonOHOH
local CallBackManager = ClientOHOH.load.CallBackManager();
local BtnHelper = ClientOHOH.load.BtnHelper();
local LanguageHelper=_G.LanguageHelper 
local PlayerInfoHelper=_G.ClientOHOH.load.PlayerInfoHelper()
local TweenHelper = ClientOHOH.load.TweenHelper();
local UIManager = ClientOHOH.load.UIManager();
local ConnectClass = _G.CommonOHOH.load.Connect()
local PVPEvent = ConnectClass.new()
local Tool=require(script.Parent.tool)
local FunctionList = ClientOHOH.load.FunctionList();
function InitInsts(ui)
	ui.insts = {};
	ui.insts.root ="ctrl.root"
	ui.insts.close = "ctrl.close"
	ui.insts.popUp = "ctrl.popUp"
	
	--nav导航栏
	ui.insts.navPK = "ctrl.nav.PK"
	ui.insts.navDefense = "ctrl.nav.defense"
	ui.insts.navSelected = "ctrl.nav.selected"
	ui.insts.navDefenseFrame = "ctrl.nav.defenseFrame"
	ui.insts.navPKFrame = "ctrl.nav.PKFrame"

	--defense防御
	ui.insts.defense = {
		cell = "ctrl.defense.cell",
		cellBox = "ctrl.defense.cellBox",
		root = "ctrl.defense.root",
		loseImg = "ctrl.defense.img.lose",
		winImg = "ctrl.defense.img.win",
		loseColor = "ctrl.defense.color.lose",
		winColor = "ctrl.defense.color.win",
		
	}
	

	--PK
	ui.insts.pk = {
		cell = "ctrl.pk.cell",
		root = "ctrl.pk.root",
		cellBox = "ctrl.pk.cellBox",
		infoVal = "ctrl.pk.information.Val",
		infoRank = "ctrl.pk.information.rank",
		infoRankIcon = "ctrl.pk.information.rankIcon",
		cdBtn = "ctrl.pk.countdown.btn",
		cdTime = "ctrl.pk.countdown.time"
	}


	--rankColor
	ui.insts.rankColor ={}
	for i = 1, 4, 1 do
		ui.insts.rankColor[i] = "ctrl.rankColor."..i
	end
end



function M.new(...)
	return M(...);
end;
function M.ctor(self)
	InitInsts(self)
	M.super.ctor(self, ClientOHOH:GetPath_Loop("ReplicatedStorage.Resource.UI.PVPGui"));
	self.insts.pk.cell.Visible = false
	self.insts.defense.cell.Visible = false
	--刷新倒计时是否结束
	self.cdIsOver = false
	--新的倒计时开始事件
	self.countDownEvent = ConnectClass.new() 
	self.PKListRenewEvent = ConnectClass.new() 
	self.myScore = 0
	self.pkEvent = ConnectClass.new() 
	self.pkEndEvent = ConnectClass.new() 
	--pvp数据列表
	self.pvpDataList = {}
	--防御数据列表
	self.defenseDataList = {}
	self:SelectNav("pk")
	self:AddConnect()
end;


function M.AddConnect(self)
	--关闭
	CallBackManager:AddRbxConnect(self,self.insts.close.Activated,function()
		UIManager.ui_list.PVPGui:Hide()
	end)
	
	--详情弹窗
	CallBackManager:AddRbxConnect(self,self.insts.popUp.Activated,function()
		if UIManager.ui_list.PVPPopUpGui.main_inst.Enabled then
			UIManager.ui_list.PVPPopUpGui:Hide()
		else
			UIManager.ui_list.PVPPopUpGui:Show()
		end
	end)

	--cd按钮，刷新
	CallBackManager:AddRbxConnect(self,self.insts.pk.cdBtn.Activated,function()
		if not self.cdIsOver then
			return
		end
		--#todo:获取新的PVP数据
		-- local event = ConnectClass.new()
		-- local data = {
		-- 	[2202500097] = 100,
        --             [3988074444] = 109,
        --             [4790816651] = 108,
        --             [4808817913] = 102,
        --             [5177343373] = 107,
        --             [5812888717] = 106
		-- }
		self:ClearPvPData()
		self.PKListRenewEvent:Action()
		-- self:FullPvPData(data)
		self.cdIsOver = false
		self.isPKing = false
		self.countDownEvent:Action()
	end)

	--tab切换pvp
	CallBackManager:AddRbxConnect(self,self.insts.navPK.Activated,function()
		self:SelectNav("pk")
	end)

	--tab切换defense
	CallBackManager:AddRbxConnect(self,self.insts.navDefense.Activated,function()
		self:SelectNav("defense")
	end)
end



local pkCellStr = {
	btn = "ctrl.btn",
	head = "ctrl.head",
	name = "ctrl.name",
	powerEmoji = "ctrl.powerEmoji",
	powerText = "ctrl.powerText"
}


--创建pvp玩家对象信息（单个，传入单条数据{[1]={name="",icon="",damage="",pvpEvent=},[2]={}}）
--名字，头像，攻击力，pvp按钮点击事件
--data.userId,data.score
function M.CreatePvPData(self,data)
	local pvpObj = self.insts.pk.cell:Clone()
	local pvp = self:InitUiInst2(pvpObj,pkCellStr)
	self:InitUiObj(pvpObj)
	pvp.Obj = pvpObj
	pvpObj.Visible = true
	pvpObj.Parent = self.insts.pk.cellBox

	--填充头像
	PlayerInfoHelper.GetPlayerInfo(data.userId,function(headImage,name)
        if pvp then
			pvp.head.Image = headImage
			pvp.name.Text = name
        end
    end)
	
	pvp.powerText.Text = data.score
	
	--pk按钮响应
	CallBackManager:AddRbxConnect(self,pvp.btn.Activated,function()
		print("对决 对方vs我 = ",data.score , self.myScore)
		local isWin =   data.score < self.myScore
		--检查PK状态
		if not self.isPKing then

			self.isPKing = true
			pvpObj.Visible = false
			
			self.pkEvent:Action(data.userId)
			self.rivalId = data.userId
			-- self.curPVPData= data.userId{
			-- 		userId = data.userId,
			-- 		score = data.score,
			-- 		isWin = isWin,
			-- 		reward = Tool.GetReward(isWin,self.myScore),
			-- 		PVPtime = os.time()
			-- 	}
		else
			print("### PK中")
		end
	end)
	return pvp
end

--清除pvp玩家的数据
function M.ClearPvPData(self)
	for _, value in pairs(self.pvpDataList) do
		value.Obj:Destroy()
	end
	self.pvpDataList= {}
end


local defenseCellStr = {
	pieceText = "ctrl.debriText",
	head = "ctrl.headImg",
	name = "ctrl.name",
	stateImg = "ctrl.stateImg",
	rankText = "ctrl.tierName",
	rankImg  = "ctrl.tierImg",
	timeStr = "ctrl.time"
}


--创建防御对象信息，生成单个对象，传入单条数据
--数据格式{name="",headIcon="",rank="",rankIcon="",isWin=,pieceNumStr="",timeStr= "",rankLevel=}
function M.CreateDefenseData(self,data)
	
	local info = Tool.GetInfo(data.score)
	local defenseObj = self.insts.defense.cell:Clone()
	local defense = self:InitUiInst2(defenseObj,defenseCellStr)
	self:InitUiObj(defenseObj)
	defense.Obj = defenseObj
	defenseObj.Visible = true
	defenseObj.Parent = self.insts.defense.cellBox

	PlayerInfoHelper.GetPlayerInfo(data.userId,function(headImage,name)
       
        if defense and defense.Obj  then
			defense.head.Image = headImage
			defense.name.Text = name
        end
       
    end)

	defense.rankText.Text =LanguageHelper:GetText(info.rankName)
	defense.rankText.TextColor3 = self.insts.rankColor[info.rankLevel]
	defense.rankImg.Image = info.icon
	defense.timeStr.Text = os.date("%m/%d/%Y %I:%M %p", data.PVPtime)
	if data.isWin then
		defense.stateImg.Image = self.insts.defense.winImg
		defense.pieceText.TextColor3 = self.insts.defense.winColor
	else
		defense.stateImg.Image = self.insts.defense.loseImg
		defense.pieceText.TextColor3 = self.insts.defense.loseColor
	end
	defense.pieceText.Text = data.reward
	return defense
end

--清除pvp玩家的数据
function M.ClearDefenseData(self)
	for _, value in pairs(self.defenseDataList) do
		value.Obj:Destroy()
	end
	self.defenseDataList= {}
end
--pvp结束
function M.PVPEnd(self)
	-- print("需要增加历史",self.curPVPData)
	self.pkEndEvent:Action(self.curPVPData)
	task.wait(2);--防止频繁进入PVP导致进入失败
	self.isPKing = false
end

--------------------对外接口---------------------
--------------------PK--------------------------
--填充玩家自己的积分段位图标,参数：积分，段位名称，图标,段位等级
function M.FullMyData(self,score)
	--,rank,icon,rankLevel myPVPData.rankName,myPVPData.icon,myPVPData.rankLevel
	local myPVPData =  Tool.GetInfo(score)
	self.myScore = score
	self.insts.pk.infoVal.Text = score
	self.insts.pk.infoRank.Text = LanguageHelper:GetText(myPVPData.rankName)
	self.insts.pk.infoRankIcon.Image = myPVPData.icon
	self.insts.pk.infoRank.TextColor3 = self.insts.rankColor[myPVPData.rankLevel]
end

--填充对战玩家的信息，会清除原本的数据，然后重新生成。传一个包含对战玩家数据的table过来
--数据格式{[1]={name="",icon="",score="",pvpEvent=},[2]={}}
function M.FullPvPData(self,data)
	local list = {}
	local index = 1
	for _, playerData in ipairs(data) do
		list[index]  = {
			userId = playerData["key"],
			score = playerData["value"],
			pvpEvent = self.pkEvent
		}
		index = index + 1
	end
	self:ClearPvPData()
	for _, value in pairs(list) do
		local pvp = self:CreatePvPData(value)
		table.insert(self.pvpDataList,pvp)
	end
end
function M.GetRivalId(self)
	return self.rivalId
end
function M.GetMyScore(self)
	return self.myScore
end

--设置倒计时文本
function M.SetCD(self,time)
	self.insts.pk.cdTime.Text = time
end

--cd结束
function M.CDIsOver(self)
	self.cdIsOver =true
	--cd结束显示字符
	self:SetCD(LanguageHelper:GetText(33508))
end

--选中tab，传字符
function M.SelectNav(self,tab)
	if tab=="defense" then
		self.insts.navPKFrame.BackgroundColor3 = Color3.new(0,0,0)
		self.insts.navDefenseFrame.BackgroundColor3 = self.insts.navSelected
		self.insts.defense.root.Visible = true
		self.insts.pk.root.Visible = false
	elseif tab == "pk" then
		self.insts.navDefenseFrame.BackgroundColor3 = Color3.new(0,0,0)
		self.insts.navPKFrame.BackgroundColor3 = self.insts.navSelected
		self.insts.pk.root.Visible = true
		self.insts.defense.root.Visible = false
	end
end

--------------------Defense--------------------------
--填充防御，会清除原本的数据，然后重新生成。传一个包含防御数据的table过来
--数据格式[1] =  {["PVPtime"] = 1730798392,["isWin"] = true,["reward"] = 100,["score"] = 1001,["userId"] = "2202500097"},
--时间戳 是否胜利 增加积分 玩家积分 玩家userId
function M.FullDefenseData(self,data)
	self:ClearDefenseData()
	for _, value in pairs(data) do
		local defense = self:CreateDefenseData(value)
		table.insert(self.defenseDataList,defense)
	end
end

function M.dtor(self)
	M.super.dtor(self);
end;




return M
